<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

/**
 * 耗时异步操作（调用本地程序）
 * @param $url   模板      模块名称/控制器/方法?参数名=参数值
 * */
function  asyncronous($url,$params=array()){
	if(empty($url)){
		return array("flag"=>false,"msg"=>"参数不正确");
	}
	if(strpos($url, "/")==0){
		return array("flag"=>false,"msg"=>"参数格式错误");
	}
	if(!empty($params)&&is_array($params)){
		$url.="?t=1";
		foreach ($params as $key => $value) {
			$url.="&".$key."=".$value;
		}
	}
	$server=$_SERVER['HTTP_HOST'];
    $fp = fsockopen($server,80,$errno,$errstr,5); 
    	if(!$fp){
    		return array("flag"=>false,"msg"=>"$errstr ($errno)");
         }
    $out = "GET /$url  / HTTP/1.1\r\n";
	$out .= "Content-type: application/json\r\n";
    $out .= "Host: $server\r\n";
    $out .= "Connection: Close\r\n\r\n";
	fwrite($fp, $out);
	$result='';
    fclose($fp); 
}
/**
 * 耗时异步操作（调用外部程序）
 */
function aysncronous_out($url,$params=array()){
  $host = config("database.asyn_base").$url;
  if(!empty($params)&&is_array($params)){
		$host.="?t=1";
		foreach ($params as $key => $value) {
			$host.="&".$key."=".$value;
		}
	}
	  $ch = curl_init();
	  curl_setopt($ch,CURLOPT_URL,$host);
	  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	  curl_setopt($ch,CURLOPT_TIMEOUT,1);
	  $result = curl_exec($ch);
	  curl_close($ch);
	  return $result;
}
/**
 * 数据库备份
 * */
function db_dump(){
	$today=date("Y-m-d");
	$count=db("SqlBack")->where("create_time like '%$today%'")->count(1);
	if(!empty($count)){
		var_dump("已经备份");
		return FALSE;
	}	
	vendor("dg.mysql-dump.src.MySQLDump");
	$dump=new MySqlDump(new mysqli(config("database.hostname"),config("database.username"),config("database.password"),config("database.database")));
	$file_name="./data/sqlbackup/".date("ymd").".sql.gz";
	$dump->save($file_name);
	db("SqlBack")->insert(array("shop_name"=>config("database.shop_name"),"shop_id"=>config("database.shop_id"),"url"=>$file_name,"ip"=>(request()->ip())));
	return date("ymd").".sql.gz";
}
